<template>
  <div class="container">
    <!-- 添加页面导航 -->
    <PageNavigation pageTitle="经纪人申请审核" />
    
    <div class="page-header">
      <h2>经纪人申请审核</h2>
      <p>审核用户提交的经纪人申请，状态为0表示待审核</p>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="queryParams" class="search-form">
      <el-form-item label="申请人姓名">
        <el-input v-model="queryParams.name" placeholder="请输入申请人姓名" clearable />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable />
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待审核" value="0" />
          <el-option label="已通过" value="1" />
          <el-option label="已拒绝" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="success" @click="exportData">导出数据</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon wait-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.pending }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon approved-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.approved }}</div>
              <div class="stat-label">已通过</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon rejected-icon">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.rejected }}</div>
              <div class="stat-label">已拒绝</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table :data="applyList" style="width: 100%" v-loading="loading">
      <el-table-column type="index" width="50" />
      <el-table-column prop="id" label="申请ID" width="80" />
      <el-table-column prop="name" label="申请人姓名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="idCard" label="身份证号" width="180" />
      <el-table-column prop="experience" label="从业年限" width="100" />
      <el-table-column prop="createTime" label="申请时间" width="160" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="danger">已拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button v-if="scope.row.status === 0" type="primary" link @click="handleDetail(scope.row)">查看详情</el-button>
          <el-button v-if="scope.row.status === 0" type="success" link @click="handleApprove(scope.row)">通过</el-button>
          <el-button v-if="scope.row.status === 0" type="danger" link @click="handleReject(scope.row)">拒绝</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="queryParams.pageSize"
        :current-page="queryParams.pageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 申请详情对话框 -->
    <el-dialog title="申请详情" v-model="dialogVisible" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申请ID">{{ currentApply.id }}</el-descriptions-item>
        <el-descriptions-item label="申请人姓名">{{ currentApply.name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentApply.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ currentApply.idCard }}</el-descriptions-item>
        <el-descriptions-item label="从业年限">{{ currentApply.experience }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ currentApply.createTime }}</el-descriptions-item>
        <el-descriptions-item label="个人简介">{{ currentApply.bio }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span v-if="currentApply.status === 0" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleRejectConfirm">拒绝</el-button>
          <el-button type="primary" @click="handleApproveConfirm">通过</el-button>
        </span>
        <span v-else class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 拒绝原因对话框 -->
    <el-dialog title="拒绝原因" v-model="rejectDialogVisible" width="500px">
      <el-form :model="rejectForm">
        <el-form-item label="拒绝原因" :label-width="'80px'">
          <el-input v-model="rejectForm.reason" type="textarea" placeholder="请输入拒绝原因" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReject">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Clock, Check, Close } from '@element-plus/icons-vue'
import PageNavigation from '@/components/common/PageNavigation.vue'
import request from '@/utils/request'

// 查询参数
const queryParams = reactive({
  name: '',
  phone: '',
  status: '',
  beginTime: '',
  endTime: '',
  pageNum: 1,
  pageSize: 10
})

const dateRange = ref([])
const applyList = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const rejectDialogVisible = ref(false)
const currentApply = ref({})
const rejectForm = reactive({
  id: null,
  reason: ''
})

// 统计数据
const statistics = reactive({
  pending: 0,
  approved: 0,
  rejected: 0
})

// 监听日期范围变化
const updateTimeRange = computed(() => {
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.beginTime = dateRange.value[0]
    queryParams.endTime = dateRange.value[1]
  } else {
    queryParams.beginTime = ''
    queryParams.endTime = ''
  }
  return dateRange.value
})

// 初始化页面
onMounted(() => {
  fetchStatistics()
  fetchApplyList()
})

// 获取统计数据
const fetchStatistics = async () => {
  try {
    // 调用后端API获取经纪人申请统计数据
    const res = await request({
      url: '/agent/review/statistics',
      method: 'get'
    })
    
    if (res.code === 200) {
      statistics.pending = res.data.pending || 0
      statistics.approved = res.data.approved || 0
      statistics.rejected = res.data.rejected || 0
    } else {
      console.error('获取统计数据失败:', res.msg)
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取申请列表
const fetchApplyList = async () => {
  loading.value = true
  try {
    // 调用后端API获取经纪人申请列表
    const res = await request({
      url: '/agent/review/list',
      method: 'get',
      params: {
        realName: queryParams.name,
        phone: queryParams.phone,
        status: queryParams.status,
        beginTime: queryParams.beginTime,
        endTime: queryParams.endTime,
        pageNum: queryParams.pageNum,
        pageSize: queryParams.pageSize
      }
    })
    
    if (res.code === 200) {
      // 映射后端返回的数据到前端显示格式
      applyList.value = res.data.records.map(item => ({
        id: item.agentId,
        userId: item.userId,
        name: item.realName,
        phone: item.phone || '未提供',
        idCard: item.idCard,
        experience: item.workYears + '年',
        createTime: item.createTime,
        status: parseInt(item.status),
        bio: item.introduction || '暂无介绍',
        company: item.company,
        licenseNo: item.licenseNo
      }))
      total.value = res.data.total
    } else {
      console.error('获取申请列表失败:', res.msg)
      ElMessage.error(res.msg || '获取申请列表失败')
      applyList.value = []
    }
  } catch (error) {
    console.error('获取申请列表失败:', error)
    ElMessage.error('获取申请列表失败')
    applyList.value = []
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchApplyList()
}

// 重置
const resetQuery = () => {
  queryParams.name = ''
  queryParams.phone = ''
  queryParams.status = ''
  dateRange.value = []
  queryParams.beginTime = ''
  queryParams.endTime = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchApplyList()
}

// 分页页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchApplyList()
}

// 导出数据
const exportData = () => {
  ElMessage.info('数据导出功能开发中')
}

// 查看申请详情
const handleDetail = (row) => {
  currentApply.value = { ...row }
  dialogVisible.value = true
}

// 通过申请
const handleApprove = (row) => {
  ElMessageBox.confirm(`确定通过 ${row.name} 的经纪人申请吗？`, '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用审核通过API
      const res = await request({
        url: '/agent/review/approve',
        method: 'post',
        data: {
          id: row.id
        }
      })
      
      if (res.code === 200) {
        ElMessage.success('操作成功')
        fetchApplyList()
        fetchStatistics()
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }).catch(() => {})
}

// 在详情对话框中通过申请
const handleApproveConfirm = async () => {
  try {
    // 调用审核通过API
    const res = await request({
      url: '/agent/review/approve',
      method: 'post',
      data: {
        id: currentApply.value.id
      }
    })
    
    if (res.code === 200) {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      fetchApplyList()
      fetchStatistics()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 拒绝申请
const handleReject = (row) => {
  rejectForm.id = row.id
  rejectForm.reason = ''
  rejectDialogVisible.value = true
}

// 在详情对话框中拒绝申请
const handleRejectConfirm = () => {
  rejectForm.id = currentApply.value.id
  rejectForm.reason = ''
  dialogVisible.value = false
  rejectDialogVisible.value = true
}

// 提交拒绝
const submitReject = async () => {
  if (!rejectForm.reason) {
    ElMessage.warning('请输入拒绝原因')
    return
  }

  try {
    // 调用拒绝API
    const res = await request({
      url: '/agent/review/reject',
      method: 'post',
      data: {
        id: rejectForm.id,
        rejectReason: rejectForm.reason
      }
    })
    
    if (res.code === 200) {
      ElMessage.success('操作成功')
      rejectDialogVisible.value = false
      fetchApplyList()
      fetchStatistics()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 24px;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.search-form {
  margin-bottom: 20px;
  background: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.stat-icon .el-icon {
  font-size: 32px;
  color: white;
}

.wait-icon {
  background: #E6A23C;
}

.approved-icon {
  background: #67C23A;
}

.rejected-icon {
  background: #F56C6C;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 